import base64
import json

import redis
import requests
import urllib
import time
import hashlib
import aes

# secretkey + appid + data  + method + session  + timestamp  + secretkey
# url = 'http://127.0.0.1:9999/rb/wallet/account_balance'
import sys



def decrypt(key, data):
    cipher = aes.AesEncryption(key)
    data = base64.urlsafe_b64decode(data.encode('utf-8'))
    result = cipher.decrypt(data)
    return result

def encrypt(key , data):
    # data = json.dumps(data_obj, ensure_ascii=False)
    #print(data)
    # print(data)
    cipher = aes.AesEncryption(key)
    data = cipher.encrypt(data)
    data = base64.urlsafe_b64encode(data)
    return data

def pay_core(url, data_obj):
    data = json.dumps(data_obj)
    cipher = aes.AesEncryption(aeskey)
    data = cipher.encrypt(data)
    data = base64.urlsafe_b64encode(data).decode('utf-8')
    request_obj = {
        'merchantid': merchantid,
        'data': data,
        'timestamp': str(int(time.time()))
    }
    sign_string = secretkey + merchantid + data + request_obj['timestamp'] + secretkey
    sign = hashlib.sha256(sign_string.encode("utf-8")).hexdigest()
    request_obj['sign'] = sign
    body = urllib.parse.urlencode(request_obj)
    print(body)
    if sys.argv[2] in ('alipayc2b', 'quickpay', 'gateway'):
        print("%s?%s" % (url, body))
        return
    response = requests.post(url, data=request_obj)
    print(response.content)
    rsp_data = json.loads(response.content.decode('utf-8'))
    #rsp_data = {"message":"success","ret":0,"timestamp":"20180904114605","sign":"126b714ad98007d3cf9f2340d3b3c934929d407ac40f36b4facb8bdaf6270043","data":"GnKpDOkyw4Tzf8pEQeXZDgATrmKt_rFBf2Buew-bd2AvxgfFxDsFR_Bl4mdB-Xz2IzMyD4A7-N84hakRERqj3l6HMIoFxe7jBFMbolfTS2eX3YZrofAJhDI7D_QvbvqF4HXrw9BMG5yzZiu8IXhiA1CloAuw7IbvH-KNVF1Tzv8=","merchantid":"M2018081713600452200"}
    if rsp_data['message'] != 'success':
        print(response.content)
        return
    rsp_sign_string = secretkey + rsp_data['merchantid'] + rsp_data['data'] + rsp_data['timestamp'] + secretkey
    rsp_sign = hashlib.sha256(rsp_sign_string.encode('utf-8')).hexdigest()
    if rsp_sign != rsp_data['sign']:
        print("sign error")
    data = base64.urlsafe_b64decode(rsp_data['data'].encode('utf-8'))
    result = cipher.decrypt(data)
    print(result)


def aliapy_c2b():
    millis = int(round(time.time() * 1000))
    print('ordernum is: %s' %millis)
    data_obj = {
        "ordernumber": str(millis),
        "body": "测试",
        "amount": "100",
        "backurl": "http://127.0.0.1:9000/testnotify"
    }

    url = 'http://api.91bill.cn/pay/alipay/h5'
    pay_core(url, data_obj)


def aliapy_query():

    data_obj = {
        "ordernumber": "1495806470617",
    }
    url = 'https://api.3035pay.com/pay/alipay/queryorder'
    pay_core(url, data_obj)


def quickpay():
    millis = int(round(time.time() * 1000))
    print('ordernum is: %s' % millis)
    data_obj = {
        "ordernumber": str(millis),
        "usercardno": "6222023602098798689",
        "amount": "100",
        "body": "test",
        "backurl": "http://127.0.0.1:9000/testnotify",
        "returnurl": "http://127.0.0.1:9000/testnotify",
    }
    url = 'http://150.109.62.163:8000/pay/unionpay/quickpay'
    pay_core(url, data_obj)

def gateway():
    millis = int(round(time.time() * 1000))
    print('ordernum is: %s' % millis)
    data_obj = {
        "ordernumber": str(millis),
        # "usercardno": "6222023602098888888",
        "amount": "100",
        "body": "test",
        'bankabbr': 'ICBC',
        "backurl": "http://127.0.0.1:9000/testnotify",
        "returnurl": "http://127.0.0.1:9000/testnotify",
    }
    url = 'http://150.109.62.163:8000/pay/unionpay/gateway'
    pay_core(url, data_obj)

def entrust():
    millis = int(round(time.time() * 1000))
    data_obj = {
        "ordernumber": str(millis),
        "username": "潘豪",
        "usercardno": "6222023602098798689",
        "amount": "100",
        "bank":"工商银行",
        "settle_type": 'BANK_PAY_DAILY_ORDER',
        "backurl": "https://api.3035pay.com/testnotify",
        "body": "出款"
        }
    url = 'http://150.109.62.163:8000/pay/unionpay/entrust'
    pay_core(url, data_obj)



def query_wallet():
    millis = int(round(time.time() * 1000))
    data_obj = {
        "ordernumber": str(millis)
    }
    url = 'https://api.3035pay.com/pay/core/query/wallet'
    pay_core(url, data_obj)

def entrust_query():
    data_obj = {
        "ordernumber": sys.argv[3],
    }
    url = "https://chanpay.8bill.cn/pay/unionpay/query/entrust"
    pay_core(url, data_obj)

def query():
    data_obj = {
        "ordernumber": sys.argv[3],
    }
    url = "http://150.109.62.163:8000/pay/unionpay/query/quick"
    pay_core(url, data_obj)

def unionpay_auth():
    millis = int(round(time.time() * 1000))

    data_obj = {
        "ordernumber": str(millis),
        'merchantid': 'M2017051513600452200',
        'username': '潘豪',
        'usercredittype': '01',
        'usercreditid': '362201198602190014',
        'usercardno': '6228480082992353712',
        'usertel': '13418071372',
    }
    url = 'https://api.3035pay.com/pay/unionpay/authelement'
    pay_core(url, data_obj)

def notify():
    request_obj = {'Method': 'paymentreport', 'Data':
        'gPvacjxfr77ltuD8_vbnG7ABbnmDpdyXJhar2M9t9LULr9dM5A1aI-KwfcpgH2efPn1IvrRII6CBX5rv8Jq8Ggnalevk9Sn38BV9OkJB4msMz91XPKKzMSGsTFI8IVu0owBtHISW1qJptXxWEGWC4gDwcPjUc5aurWeZfcXr_HYvMJW6cjZ7SPQ6a60rfoOdOD4IpxZGXkpAiEeKcxzzPEtU--Lhcbl5ukw3-RiYs5cx5Tnr0NrdI4UdkxbHylmj2M0jH6K3gaW0IxazNpfdD044ZULVXNFuna9HmwE81ZlwwtnSLnsxVxeel_9ONFL-_EuXXhH_mzAbe8HRAEU5-tWNQc3mL-Wb2zpAxLOIsRU_ZQeptsDN88DK7z3sydhAg1owpOxGe18YH0aWSjgCIPv_nfG0aI6tqFSED0aY-knXnGgxdzHa0JAhnZfB0IKpDn5U-eWGoAt_rZ80cc3OufiRRmhoUU5sc4h4BYW43YoDzsRI2ufnx7Ov3wzFQ6nDiaS7EO4Vv9z9X4coTqjGFSsH4i6ULPuPm0vDFAGTDxSrD92GkFqlVQCP4Pgj1U-uzS2mal2gkZT9dp4EE2eSekQcapIMOCWZAJE3DpIY_kdebUw7aXNjjjO5ibTP4SQiBreQHN8K7e5wpXV3lDRD6SEDTgpKpgK2n7ncpVkrYUtCUVVdlEE3FIF24R_LUqxlst7-pb-OoVRRi7OzKlLiuMibPnHCOx0AcSYecY1Z1vs1eeHbaU2BIeq6lgx5bqWlTLkBQz5bytKG7-RSQNRBsubPgVBUmRNrEaD2wfS_TtpJHBMganfAC4TK7rNkyuQd-TfnY3kNT-cnrSyod2UQww==',
     'Sign': 'f2bba3a188d31bc81e2be04e1020832d', 'Appid': '200370471'}
    url = "https://api.3035pay.com/rbgznotify/"
    response = requests.post(url, data=request_obj)

if __name__ == "__main__":

    merchantid = sys.argv[1]
    channel = sys.argv[2]

    redis_con = redis.Redis(host='localhost', port=12580, db=0, password="PayCore#8bill",)
    secretkey = redis_con.hget(merchantid, "SHAKEY").decode()
    aeskey = redis_con.hget(merchantid, "AESKEY").decode()
    if channel == 'alipayc2b':
        aliapy_c2b()

    elif channel == 'entrustquery':
        entrust_query()
    elif channel == 'quickpay':
        quickpay()
    elif channel == 'gateway':
        gateway()
    elif channel == 'entrust':
        entrust()
    elif channel == 'query':
        query()
